#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :       2020/12/18 18:04
    Desc  :       测试集
--------------------------------------
"""
import time

from flask import Blueprint, render_template, request
from application import app
from common.libs.CaseRequestUtils import CaseRequestUtils, ApiCaseIsExist
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.QuerySetUtils import QuerySetUtils
from common.libs.TimeUtils import TimeUtils
from common.libs.paginationUtils import ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils
from servers.models.ApiCaseModel import ApiCase
from servers.models.ApiCaseSuiteModel import ApiCaseSuite
from servers.servers.ApiCaseSuiteServices import ApiCaseSuiteServices
from servers.servers.CasesRecordServices import add_case_record, CasesRecordServices

case_suite_route = Blueprint('case_suite', __name__)


@case_suite_route.route('/list', methods=['POST'])
def caseSuiteList():

    try:
        form = {} if not request.json else dict(request.json)
        # 1. 获取当前项目id
        projectId = request.headers.get('project')
        form['projectId'] = projectId
        dat = ApiCaseSuiteServices().pagination(**form)
        return JsonResponse(code=20000, data=dat, message='请求成功').jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户详情
@case_suite_route.route('/info', methods=['POST'])
def caseSuiteInfo():
    try:
        form = {} if not request.json else dict(request.json)

        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        case = ApiCaseSuite.objects(id=form.get('id'))
        if case.count() == 0:
            return JsonResponse(code=40005, data=None, message="用户不存在").jsonExit()
        return JsonResponse(code=20000, data=case.first().to_json(), message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(Exception(e))
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


@case_suite_route.route('/add', methods=['POST'])
def caseSuiteAdd():

    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(ApiCaseSuite).filterField(form)

        # 1. 获取当前项目id
        projectId = request.headers.get('project')
        form['projectId'] = projectId
        if form.get('caseSuiteName') is None or form.get('caseSuiteName') == '':
            return JsonResponse(code=40002, data=None, message="caseSuiteName不能为空").jsonExit()
        # ApiCase对象列表
        caseList = form.get('caseList')
        apiCaseIds = []
        for i in range(len(caseList)):
            if caseList[i].get('_id'):
                apiCaseIds.append(caseList[i].get('_id').get('$oid'))

        form['caseList'] = apiCaseIds
        case = ApiCaseSuite(**form)
        case.save()
        return JsonResponse(code=20000, data=case, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户编辑
@case_suite_route.route('/edit', methods=['POST'])
def caseSuiteEdit():
    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(ApiCaseSuite).filterField(form)

        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        case = ApiCaseSuite.objects(id=form.get('id'))
        if case.count() == 0:
            return JsonResponse(code=40005, data=None, message="用户不存在").jsonExit()
            # ApiCase对象列表
        caseList = form.get('caseList')
        apiCaseIds = []
        for i in range(len(caseList)):
            if caseList[i].get('_id'):
                apiCaseIds.append(caseList[i].get('_id').get('$oid'))

        form['caseList'] = apiCaseIds
        case.update(**form)
        return JsonResponse(code=20000, data=case, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 用户删除
@case_suite_route.route('/delete', methods=['POST'])
def caseSuiteDelete():
    try:
        form = {} if not request.json else dict(request.json)
        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        case = ApiCaseSuite.objects(id=form.get('id'))
        if case.count() == 0:
            return JsonResponse(code=40005, data=None, message="测试集不存在").jsonExit()
        case.delete()
        return JsonResponse(code=20000, data=None, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 测试集执行
@case_suite_route.route('/run', methods=['POST'])
def caseSuiteRun():
    try:
        form = {} if not request.json else dict(request.json)
        id = form.get("id")
        projectId = request.headers.get('project')
        if id is None or id == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        casesuiteServices = ApiCaseSuiteServices()
        caserecordServices = CasesRecordServices()
        createData = TimeUtils().timeStamp()
        data = casesuiteServices.run(id)
        caserecordServices.save(projectId = projectId, casesuiteId = id, resultObject = data, createData = createData)
        return JsonResponse(code=20000, data=data, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()
